package de.fuberlin.inf.alp3.ue03;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

import de.fuberlin.inf.alp3.ue01.StringQueue;
import de.fuberlin.inf.alp3.utils.ConsoleInput;

public class ReadableStringQueue
        extends StringQueue implements ValueReader.Readable {
    
    public void clear() { this.first = this.last = null; }

    @Override
    public void fromConsole(int indent) {
        this.fromString(ConsoleInput.readString("Read StringQueue:"));
    }
    
    public void fromString(String str) {
        if (!str.matches("\\[((\".*?\",\\s*?)*?(\".*?\"))?\\]"))
            throw new RuntimeException(
                    "Invalid format!\n" +
                    "E.G. [\"A\",\"B\",\"C\"]\n" +
                    " => the list must be enclosed by squared brackets\n" +
                    " => the list can be empty\n" +
                    " => elements must be enclosed by quotes\n" +
                    " => every element except for the last one must be " +
                        "followed by comma");
        this.clear();
        Pattern p = Pattern.compile("(\".*?\"[,\\]])");
        Matcher m = p.matcher(str);
        while ( m.find() )
            this.append(str.substring(m.start() + 1, m.end() - 2));
    }

    @Override
    public String toString() {
        StringBuffer sb = new StringBuffer("[");
        for (Cell curr = this.first; curr != null; curr = curr.next())
            sb.append("\"" + curr + "\",");
        if (sb.length() > 1)
            sb.setCharAt(sb.length() - 1, ']');
        else
            sb.append(']');
        return sb.toString();
    }
}